package com.woniuxy.lab.woniu_lab_boss.Security.filter;

import cn.hutool.core.util.ObjectUtil;
import com.woniuxy.lab.woniu_lab_boss.exception.AccountException;
import com.woniuxy.lab.woniu_lab_boss.exception.WebExceptionCode;
import com.woniuxy.lab.woniu_lab_boss.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 17292
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    public static final String LAP_BOSS_TOKEN = "lap-boss-token";
    public static final String ACCOUNT_ID = "accountId";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //得到token
        String token = request.getHeader(LAP_BOSS_TOKEN);
        if (token == null) {
            filterChain.doFilter(request, response);
            return ;
        }
        //解析token
        Claims claims = JwtUtil.parseToken(token);
        Object accountId = claims.get(ACCOUNT_ID);
        if (ObjectUtil.isEmpty(accountId)){
            throw new RuntimeException("用户未登录");
        }

        // 存入SecurityContextHolder, 其他filter会通过这个来获取当前用户信息
        // 获取权限信息封装到authentication中,第二个null为权限集合
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                = new UsernamePasswordAuthenticationToken(accountId,null,null);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        // 放行
        filterChain.doFilter(request, response);
    }
}
